//
// Created by cube on 2020/10/26.
//

#include <gtest/gtest.h>
#include "../Base/EventSystem/EventSystem.h"
#include "../Base/EventSystem/SignalEventDrivers.h"

using namespace Lib;

EventLoop* l = nullptr;

class MyDriver : public EventDriver{
public:
    void sendEvent(Event* event){EventDriver::sendEvent(event);}
    void sendEvent(const std::chrono::microseconds& millis,Event* event){EventDriver::sendEvent(millis,event);}

    void installHandler(EventLoop::EventHandler* handler){EventDriver::installHandler(handler);}
    void uinstallHandler(EventLoop::EventHandler* handler){EventDriver::uinstallHandler(handler);}
    bool hasHandler(EventLoop::EventHandler* handler){return EventDriver::hasHandler(handler);}

    template <typename ...Args>
    void emit(Signal<Args...>& signal,Args ...args){EventDriver::emit(signal,args...);}
};

class MyHandler : public EventLoop::EventHandler{
public:
    bool filter(EventAgent& event) override {
        return EventLoop::EventHandler::filter(event);
    }
    void event(EventAgent& event) override {
        std::cout<<"event" <<event->getType()<<std::endl;
        std::cout<<InvokeEvent::type()<<std::endl;
        if(event->getType() == InvokeEvent::type()){
//            event.reSendTo(std::chrono::seconds(3),l);
        }
//        if(event->getType() == DEvent<int>::type()){
//            event.reSendTo(std::chrono::seconds(3),l);
//        }
    }
};

TEST(Event_TEST,Base){
    EventLoop loop;         //创建事件循环
    l = &loop;
    auto driver = new MyDriver();     //创建事件驱动器
    driver->setLoop(&loop);  //设置循环

    auto p = new MyHandler();    //创建事件处理器
    driver->installHandler(p);         //绑定到事件循环

    //发送定时事件
    driver->sendEvent(std::chrono::seconds(2),new InvokeEvent([](){std::cout<<"invoke"<<std::endl;}));
    driver->sendEvent(std::chrono::seconds(3),new DEvent<int>(1));
    driver->sendEvent(std::chrono::seconds(3),new DEvent<int>(3));

//    发生事件
    driver->sendEvent(new DEvent<int,int>(4,3));

    driver->loop()->exec();              //事件循环 开始执行
}

TEST(Event_TEST,Signal){
    auto driver = std::make_shared<MyDriver>();     //创建事件驱动器
    //创建信号
    LIB_SIGNAL(signal_a)
    LIB_SIGNAL(signal_b,int)
    Signal<int> signal_c;
    Signal<std::string> signal_d;

    signal_a.connect([](){std::cout<<"signal a"<<std::endl;});
    signal_b.connect([](int a){std::cout<<"signal b "<<a<<std::endl;});
    signal_c.connect([](int a){std::cout<<"signal c "<<a<<std::endl;});
    signal_b.connect(signal_c);
    signal_d.connect([](std::string s){std::cout<<"signal d "<<s<<std::endl;});

    driver->emit(signal_a);
    driver->emit(signal_b,3);
    driver->emit(signal_d,std::string("sss"));

    EventLoop::singleCase().exec();
}

TEST(Event_TEST,EventLoop_T){
    std::cout<<"sss"<<std::endl;

}